package com.kk.xhr.model.service.impl;

import com.kk.xhr.common.pojo.BinaryEnum;
import com.kk.xhr.model.assembler.ContractStructKit;
import com.kk.xhr.model.dao.ContractDynamicSqlSupport;
import com.kk.xhr.model.dao.ContractMapper;
import com.kk.xhr.model.dto.ContractDTO;
import com.kk.xhr.model.dto.PageDto;
import com.kk.xhr.model.entity.Contract;
import com.kk.xhr.model.service.IContractService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

import java.util.Optional;
import java.util.stream.Collectors;

import static org.mybatis.dynamic.sql.SqlBuilder.isEqualTo;
import static org.mybatis.dynamic.sql.SqlBuilder.isEqualToWhenPresent;

/**
 * 合同服务接口实现
 *
 * @author kkmystery
 * @version 1.0 2021/3/4
 * @since 1.0.0
 */
@Repository
@RequiredArgsConstructor
public class ContractServiceImpl implements IContractService {
    private final ContractMapper contractMapper;
    private final ContractStructKit instance = ContractStructKit.INSTANCE;

    @Override
    public Optional<ContractDTO> queryById(Long id) {
        return contractMapper.selectOne(dsl -> dsl
            .where(ContractDynamicSqlSupport.id, isEqualTo(id))
            .and(ContractDynamicSqlSupport.status, isEqualTo(BinaryEnum.TRUE.getValue())))
            .map(instance::toDto);
    }

    @Override
    public boolean add(ContractDTO dto) {
        return 1 == contractMapper.insertSelective(instance.toEntity(dto));
    }

    @Override
    public boolean modify(ContractDTO dto) {
        if (null == dto.getId()) {
            return false;
        }
        return 1 == contractMapper.updateByPrimaryKeySelective(instance.toEntity(dto));
    }

    @Override
    public boolean modifyStatus(Long id, BinaryEnum status) {
        if (null == status) {
            return false;
        }
        return 1 == contractMapper.updateByPrimaryKeySelective(new Contract().withId(id).withStatus(status.getValue()));
    }

    @Override
    public PageDto<ContractDTO> queryPage(Long userId, Integer limit, Integer offset) {
        long count = contractMapper.count(dsl -> dsl
            .where(ContractDynamicSqlSupport.userId, isEqualToWhenPresent(userId))
            .and(ContractDynamicSqlSupport.status, isEqualTo(BinaryEnum.TRUE.getValue())));
        if (0 == count) {
            return PageDto.empty();
        }
        return new PageDto<>(count, contractMapper.select(dsl -> dsl
            .where(ContractDynamicSqlSupport.userId, isEqualToWhenPresent(userId))
            .and(ContractDynamicSqlSupport.status, isEqualTo(BinaryEnum.TRUE.getValue()))
            .limit(limit)
            .offset(offset))
            .stream().map(instance::toDto)
            .collect(Collectors.toList()));
    }
}
